<?php

class Loader {

    private $lib_instance = [];
    private $service_instance = [];
    private $model_instance = [];

    public function config($filename){
        return _autoload('config/' . $filename);
    }

    public function lib($classname, $instance = TRUE, $newInstance = FALSE){
        if (!$instance) {
            _autoload('lib/' . $classname);
            return;
        }

        if (!$newInstance && isset($this->lib_instance[$classname])) {
            return $this->lib_instance[$classname];
        }

        _autoload('lib/' . $classname);
        $this->lib_instance[$classname] = new $classname;
        return $this->lib_instance[$classname];
    }

    public function model($classname, $newInstance = FALSE) {
        if (!$newInstance && isset($this->model_instance[$classname])) {
            return $this->model_instance[$classname];
        }

        _autoload('model/' . $classname);
        $this->model_instance[$classname] = new $classname;
        return $this->model_instance[$classname];
    }

    public function service($classname, $newInstance = FALSE) {
        if (!$newInstance && isset($this->service_instance[$classname])) {
            return $this->service_instance[$classname];
        }

        _autoload('service/' . $classname);
        $this->service_instance[$classname] = new $classname;
        return $this->service_instance[$classname];
    }

    public function view($viewpath, $params = []) {
        if (!$viewpath) {
            return '404 NOT FOUND';
        }
        try {
            ob_start();
            _autoload('view/' . $viewpath);
            $buffer = ob_get_contents();
            ob_end_flush();
            @ob_end_clean();
            return $buffer;
        } catch (\Exception $e) {
            return '404 NOT FOUND';
        }
    }
}
